package com.legendshop.openportal.sdk.client.http.handler;

import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.legendshop.openportal.sdk.client.http.HttpResponseAnalyzer;
import com.legendshop.openportal.sdk.client.http.HttpResponseAnalyzerContext;
import com.legendshop.openportal.sdk.client.http.HttpResponseHandler;
import com.legendshop.openportal.sdk.model.OpenResult;
import com.legendshop.openportal.sdk.model.constants.CommonStatusEnum;
import com.legendshop.openportal.sdk.model.BaseResponse;

import java.lang.reflect.Type;
import java.util.List;

/**
 * @author jzh
 * @version 1.0.0
 * @title DefaultHttpResponseHandler
 * @date 2024/6/18 11:10
 * @description：
 */
public class DefaultHttpResponseHandler<T> implements HttpResponseHandler<T> {

    private final Type responseClass;
    private final List<HttpResponseAnalyzer> analyzers;

    public DefaultHttpResponseHandler(final Class<T> responseClass, final List<HttpResponseAnalyzer> analyzers) {
        this.responseClass = responseClass;
        this.analyzers = analyzers;
    }

    public DefaultHttpResponseHandler(final Type responseClass, final List<HttpResponseAnalyzer> analyzers) {
        this.responseClass = responseClass;
        this.analyzers = analyzers;
    }

    @Override
    public OpenResult<T> handle(HttpResponse response) {
        try {
            // 提前转换好，减少重复转换
            if (JSONUtil.isJsonObj(response.body())) {
                JSONObject jsonObject = JSONUtil.parseObj(response.body());
                HttpResponseAnalyzerContext.set(jsonObject);
            }

            for (HttpResponseAnalyzer analyzer : analyzers) {
                OpenResult<T> openResult = analyzer.analyze(response, responseClass);
                if (openResult != null) {
                    return openResult;
                }
            }

            return OpenResult.fail(CommonStatusEnum.UNABLE_ANALYZER, response.body());
        } finally {
            // 清除上下文
            HttpResponseAnalyzerContext.clear();
        }
    }
}
